package com.laozhao.msas.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

public class SystemInfoUtil {

	public static String[] getSystemInfo() {
		try {
			String[] info = new String[3];
			info[0] = InetAddress.getLocalHost().getHostName();
			String procCmd = System.getenv("windir")+ "\\system32\\wbem\\wmic.exe cpu";
			info[1] = readSystem(Runtime.getRuntime().exec(procCmd),new String[]{"Caption","ProcessorId"}); 
			procCmd = System.getenv("windir")+ "\\system32\\wbem\\wmic.exe BIOS";
			info[2] = readSystem(Runtime.getRuntime().exec(procCmd),new String[]{"Caption","BiosCharacteristics"}); 
			return info;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 
	 * 读取CPU信息.
	 * 
	 * @param proc
	 * @return
	 * @author GuoHuang
	 */
	private static String readSystem(final Process proc,String[] names) {
		String retn = "";
		try {
			proc.getOutputStream().close();
			InputStreamReader ir = new InputStreamReader(proc.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			String line = input.readLine();
			if (line == null || line.length() < 10) {
				return null;
			}
			List<Integer[]> indexs = getPairIndex(line, names);
			while ((line = input.readLine()) != null) {
				if (line.length() < indexs.get(indexs.size()-1)[1]) {
					continue;
				}
				for (int i = 0; i < indexs.size(); i++) {
					Integer[] index = indexs.get(i);
					retn += line.substring(index[0], index[1]);
				}
			}
			return retn;
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			try {
				proc.getInputStream().close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	private static List<Integer[]> getPairIndex(String command ,String... paramer){
		List<Integer[]>  reList = new ArrayList<Integer[]>(paramer.length);
		Integer[] indexs;
		int endIndex;
		for (int i = 0; i < paramer.length; i++) {
			indexs = new Integer[2];
			indexs[0] = command.indexOf(paramer[i]);
			endIndex = indexs[0] + paramer[i].length();
			while (command.charAt(endIndex) == ' ') {
				endIndex ++;
			}
			indexs[1] = endIndex -1; 
			reList.add(indexs);
			System.out.print(indexs[0] + "~" + indexs[1]+"\t");
		}
		System.out.println();
		return reList;
	}
}
